package com.api.oa.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.sax.handler.RowHandler;
import com.api.oa.exception.BadRequestException;
import com.api.oa.model.entity.YQInsEntity;
import com.api.oa.model.entity.YQMedCare;
import com.api.oa.services.YQMedCareService;
import com.api.shopapi.controller.BaseController;
import com.api.shopapi.entity.MyResult;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/yq/yQMedCare")
public class YQMedCareController extends BaseController {

    @Autowired
    private YQMedCareService iYQMedCareService;

    @SneakyThrows
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public MyResult Add(@RequestBody YQMedCare entity) throws BadRequestException {
        return iYQMedCareService.add(entity) == 1 ? success(entity) : failed("操作失败");
    }


    @RequestMapping(value = "/addBatch", method = RequestMethod.POST)
    public MyResult Add(@RequestBody List<YQMedCare> entities, HttpServletRequest req) {
        try {
            String timestamp = req.getHeader("timestamp");
            final String sign = req.getHeader("sign");
            if (StrUtil.isEmpty(timestamp)) return failed("时间戳不能为空");
            if (StrUtil.isEmpty(sign)) return failed("认证未通过");
            String format = String.format("timestamp=%s&key=%s", timestamp, privateKey);
            String s = SecureUtil.md5(format);
            if (!s.equals(sign)) return failed("认证未通过");
            iYQMedCareService.addBatch(entities);
            return success("操作成功");
        } catch (BadRequestException e) {
            return anomalous(e.getMessage());
        }

    }


    @RequestMapping(value = "/remove/{id}", method = RequestMethod.POST)
    public MyResult remove(@PathVariable String id) {
        try {
            iYQMedCareService.remove(id);
            return success("删除成功!");
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }

    }


    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public MyResult update(@RequestBody YQMedCare entity) {
        try {
            return iYQMedCareService.update(entity) == 1 ? success("操作成功") : failed("操作失败");
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }

    }


    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public MyResult list(@RequestParam(defaultValue = "1") Integer pageIndex, @RequestParam(defaultValue = "20") Integer pageSize, @RequestParam(required = false) Long pid) {
        try {
            return success(iYQMedCareService.list(pid, pageIndex, pageSize));
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }
    }
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public void export(@RequestParam(defaultValue = "1") Integer pageIndex, @RequestParam(defaultValue = "20") Integer pageSize, @RequestParam(defaultValue = "") String idCard, @RequestParam(required = false) String insCode
            , @RequestParam(required = false) String role, HttpServletResponse res) {
        try {
            iYQMedCareService.export(idCard, insCode, role, pageIndex, pageSize,res);
        } catch (Exception e) {
        }
    }

    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public MyResult page(@RequestParam(defaultValue = "1") Integer pageIndex, @RequestParam(defaultValue = "20") Integer pageSize, @RequestParam(defaultValue = "") String idCard, @RequestParam(required = false) String insCode
            , @RequestParam(required = false) String role) {
        try {
            return success(iYQMedCareService.page(idCard, insCode, role, pageIndex, pageSize));
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }
    }


    @RequestMapping(value = "/one/{id}", method = RequestMethod.GET)
    public MyResult one(@PathVariable Long id) {
        try {
            return success(id == null ? null : iYQMedCareService.one(id));
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }
    }


    /**
     * 给病患申请分配医护 的医护列表
     *
     * @param insCode
     * @return
     */
    @RequestMapping(value = "/ins/cares", method = RequestMethod.GET)
    public MyResult queryMedByInsCode(@RequestParam(required = false) String insCode) {
        try {
            return success(iYQMedCareService.queryMedByInsCode(insCode));
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }
    }


    @RequestMapping("/upload")
    public MyResult uploadFile(@RequestParam("file") MultipartFile file) throws IllegalStateException, IOException, BadRequestException {
        List<YQMedCare> entities = new ArrayList<>();
        ExcelUtil.readBySax(file.getInputStream(), 0, new RowHandler() {
            @SneakyThrows
            @Override
            public void handle(int i, long l, List<Object> list) {
                if (i == 0 && l > 1) {

                    try {
                        Object medCare = list.get(0);
                        Object sex = list.get(1);
                        Object idCard = list.get(2);
                        Object district = list.get(3);
                        Object phone = list.get(4);
                        Object medRole = list.get(5);
                        Object personType = list.get(6);
                        Object insCode = list.get(7);
                        Object enabled = list.get(8);
                        if (StrUtil.isEmptyIfStr(idCard) || StrUtil.isEmptyIfStr(insCode)) return;
                        if (!IdcardUtil.isValidCard(String.valueOf(idCard))) {
                            return;
                        }

                        YQMedCare yqInsEntity = new YQMedCare();
                        yqInsEntity.setMedName(StrUtil.isBlankIfStr(medCare) ? "" : String.valueOf(medCare));
                        yqInsEntity.setMedIdCard(StrUtil.isBlankIfStr(idCard) ? "" : String.valueOf(idCard));
                        yqInsEntity.setMedPhone(StrUtil.isBlankIfStr(phone) ? "" : String.valueOf(phone));
                        yqInsEntity.setMedRole(("医师".equals(personType) || "乡医".equals(personType)) ? 0 : ("护理员".equals(personType) || "康复人员".equals(personType)) ? 2 : 1);
                        yqInsEntity.setMedSex("男".equals(sex) ? 1 : 0);
                        yqInsEntity.setDisabled(String.valueOf(enabled).equals("有效") ? 0 : 1);
                        yqInsEntity.setMedIns(StrUtil.isBlankIfStr(insCode) ? "" : String.valueOf(insCode).trim());
                        yqInsEntity.setCreatedAt(DateUtil.date());
                        entities.add(yqInsEntity);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }

            }
        });
        iYQMedCareService.addBatch(entities);
         return success(String.format("导入成功%d条数据",entities.size()));
    }

}
